﻿using AutoMapper;
using AutoMapper.Configuration;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.NoNet;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using NetTaste;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.XWPF.UserModel;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;


namespace DFGK_WMS.Repository
{
    public class TReceivingOrderDetailRepository : BaseRepository<TReceivingOrderDetail>, ITReceivingOrderDetailRepository
    {
        private readonly IBarCodeRuleRepository _BarCodeRuleRepositoy;
        private readonly SqliteContext sqlite;
        private readonly IConfiguration configuration;

        public TReceivingOrderDetailRepository(DFGK_DB context, IMapper mapper, IBarCodeRuleRepository barCodeRuleRepositoy, SqliteContext sqlite) : base(context, mapper)
        {
            _BarCodeRuleRepositoy = barCodeRuleRepositoy;
            this.sqlite = sqlite;
        }

        //获取设备绝对路径
        public string cccc()
        {
            // 查询移动设备的连接情况
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity WHERE ClassGuid='{EEC5AD98-8080-425F-922A-DABF3DE3F69A}'");
            string absolutePath = null;
            foreach (ManagementObject device in searcher.Get())
            {
                string deviceName = device["Name"].ToString();
                string deviceId = device["DeviceID"].ToString();


                Console.WriteLine("设备名称: " + deviceName);
                Console.WriteLine("设备ID: " + deviceId);

                // 获取移动设备的驱动器号
                ManagementObjectCollection driveCollection = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%USB%'").Get();

                foreach (ManagementObject drive in driveCollection)
                {
                    // 获取移动设备的驱动器号
                    string driveLetter = drive["Caption"].ToString().Substring(0, 2); // 获取驱动器号，例如 "E:"

                    Console.WriteLine("移动设备驱动器号: " + driveLetter);

                    // 获取移动设备在计算机中的路径
                    absolutePath = System.IO.Path.Combine(driveLetter, deviceId);
                    Console.WriteLine("移动设备在计算机中的绝对路径: " + absolutePath);
                }

            }
            return absolutePath;
        }



        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool FileDownload(string SourceFile, string DestinationFolder)
        {
            string sourceFilePath = @"wwwroot\\file\\cs.txt"; // 替换为源文件的实际路径
            string destinationFilePath = @"\\content://com.android.externalstorage.documents/document/primary%3A\\laoyase"; // 替换为目标文件的实际路径
            try
            {
                if (File.Exists(destinationFilePath))
                {
                    File.Delete(destinationFilePath);
                    Console.WriteLine("已删除现有的目标文件。");
                }

                File.Copy(sourceFilePath, destinationFilePath);
                Console.WriteLine("文件复制成功！");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("文件复制失败：" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 往sqlite中写入数据
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool AddSqliteDetail(GroupReceivingOrderDto m, out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                //创建表（如果不存在）
                bool aa = sqlite.Database.EnsureCreated();
                // 设置连接字符串
                string connectionString = "Data Source=.\\wwwroot\\file\\chat.db";

                // 创建连接对象
                using (var connection = new SqliteConnection(connectionString))
                {
                    // 打开连接
                    connection.Open();

                    // 创建SQL命令对象
                    using (var command = connection.CreateCommand())
                    {
                        // 设置清空缓存的SQL语句
                        command.CommandText = "PRAGMA cache_size=0;";

                        // 执行SQL命令
                        command.ExecuteNonQuery();

                        Console.WriteLine("Cache cleared.");
                    }

                    // 关闭连接
                    connection.Close();
                }
                List<SqliteChildrenReceivingOrder> childrenss = new List<SqliteChildrenReceivingOrder>();
                foreach (var item in m.childrenReceivingOrders)
                {
                    SqliteChildrenReceivingOrder childrens = new SqliteChildrenReceivingOrder();
                    childrens.MakerialCategoryId = item.MakerialCategoryId;
                    childrens.MaterialCategoryName = item.MaterialCategoryName;
                    childrens.MaterialCategoryCode = item.MaterialCategoryCode;
                    childrens.MaterialId = item.MaterialId;
                    childrens.Name = item.Name;
                    childrens.Code = item.Code;
                    childrens.ModelSpec = item.ModelSpec;
                    childrens.QualityState = item.QualityState;
                    childrens.Price = item.Price;
                    childrens.ReceivePrice = item.ReceivePrice;
                    childrens.UnitName = item.UnitName;
                    childrens.ReceivedQty = item.ReceivedQty;
                    childrens.Qty = item.Qty;
                    childrens.TotalPrice = item.TotalPrice;
                    childrens.ReceivedTotalPrice = item.ReceivedTotalPrice;
                    childrens.TypeName = item.TypeName;
                    childrens.Remark = item.Remark;

                    childrenss.Add(childrens);
                }

                var Json = JsonConvert.SerializeObject(m.childrenReceivingOrders);

                var receivingList = Context.TReceivingOrderDetails.Where(x => x.OrderSn == m.OrderSn).ToList();
                foreach (var item in receivingList)
                {
                    item.Status = 1;
                    Context.TReceivingOrderDetails.Update(item);
                    if (Context.SaveChanges() <= 0)
                    {
                        message = "更新状态失败";
                        tran.Rollback();
                        return false;
                    }
                }

                var InboundListMode = new InboundListModes
                {
                    OrderSn = m.OrderSn,
                    RelevanceOrderSn = m.RelevanceOrderSn,
                    BillType = m.BillType,
                    Agent = m.Agent,
                    SupplierId = m.SupplierId,
                    SupplierCode = m.SupplierCode,
                    SupplierName = m.SupplierName,
                    Contact = m.Contact,
                    ContactMobile = m.ContactMobile,
                    ProductDate = m.ProductDate,
                    Remark = m.Remark,
                    NowUserId = m.NowUserId,
                    NowUserName = m.NowUserName,
                    NowRoule = m.NowRoule,
                    ExamineState = m.ExamineState,
                    State = m.State,
                    jsonData = Json,

                };

                string OrderSnByError = "";
                List<RecevingQueryTable> RecevingQueryTable = new List<RecevingQueryTable>();

                List<SqliteChildrenReceivingOrder> dataList = JsonConvert.DeserializeObject<List<SqliteChildrenReceivingOrder>>(InboundListMode.jsonData).ToList();
                foreach (var Details in dataList)
                {
                    //var RecevingList = Context.TReceivingGoodsDetails.FirstOrDefault(x => x.OrderDetailId == Details.Id);
                    // foreach (var item in RecevingList)                                                                                                                               
                    //{
                    var newRecevingQueryTable = new RecevingQueryTable(); // 创建一个新的 RecevingQueryTable 对象
                    newRecevingQueryTable.OrderSn = m.OrderSn;
                    OrderSnByError = m.OrderSn;
                    //newRecevingQueryTable.OrderSnDetailId = RecevingList.OrderDetailId;
                    newRecevingQueryTable.OrderSnDetailId = Details.Id;
                    //newRecevingQueryTable.BarCode = RecevingList.Barcode;
                    newRecevingQueryTable.MaterialName = Context.TReceivingOrderDetails.Where(x => x.Id == Details.Id).First().MaterialName;
                    newRecevingQueryTable.MaterialCategoryName = Details.MaterialCategoryName;
                    newRecevingQueryTable.QualityState = Details.QualityState;
                    newRecevingQueryTable.Qty = Details.Qty;
                    //newRecevingQueryTable.Position = Context.TInventory.Where(x => x.MaterialId == Details.MaterialId).First().LocationCode;
                    newRecevingQueryTable.ReceivedQty = Details.ReceivedQty;
                    newRecevingQueryTable.BarCode = Details.Code;
                    RecevingQueryTable.Add(newRecevingQueryTable);


                    // }
                }

                //修改数据库相关状态信息


                sqlite.RecevingQueryTable.AddRange(RecevingQueryTable);
                sqlite.InboundListModes.Add(InboundListMode);
                if (sqlite.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "入库添加数据失败! 单号" + OrderSnByError;
                    return false;

                }

                //Console.Write("Json==========================================================="+InboundListMode.jsonData);

                if (InboundListMode == null && RecevingQueryTable == null)
                {
                    tran.Rollback();
                    message = "入库数据未添加成功!";
                    return false;
                }
                tran.Commit();
                message = "入库数据添加成功";
                return true;
            }
            catch (Exception ex)
            {
                tran.Rollback();
                message = "入库数据添加失败";
                return false;
            }



        }


        /// <summary>
        /// 读取sqlite数据
        /// </summary>
        /// <returns></returns>
        public List<GroupReceivingOrderDto> GetReceivingOrderDtos()
        {
            //创建表（如果不存在）
            sqlite.Database.EnsureCreated();

            var list = sqlite.InboundListModes.AsQueryable();

            List<GroupReceivingOrderDto> dto = new List<GroupReceivingOrderDto>();
            foreach (var order in list)
            {
                GroupReceivingOrderDto groupReceivingOrder = new GroupReceivingOrderDto();
                groupReceivingOrder.OrderSn = order.OrderSn;
                groupReceivingOrder.RelevanceOrderSn = order.RelevanceOrderSn;
                groupReceivingOrder.BillType = order.BillType;
                groupReceivingOrder.Agent = order.Agent;
                groupReceivingOrder.SupplierId = order.SupplierId;
                groupReceivingOrder.SupplierName = order.SupplierName;
                groupReceivingOrder.SupplierCode = order.SupplierCode;
                groupReceivingOrder.Contact = order.Contact;
                groupReceivingOrder.ContactMobile = order.ContactMobile;
                groupReceivingOrder.ProductDate = order.ProductDate;
                groupReceivingOrder.Remark = order.Remark;
                groupReceivingOrder.NowUserId = order.NowUserId;
                groupReceivingOrder.NowUserName = order.NowUserName;
                groupReceivingOrder.NowRoule = order.NowRoule;
                groupReceivingOrder.ExamineState = order.ExamineState;
                groupReceivingOrder.State = order.State;
                List<ChildrenReceivingOrder> JsonList = JsonConvert.DeserializeObject<List<ChildrenReceivingOrder>>(order.jsonData);
                groupReceivingOrder.childrenReceivingOrders = JsonList;
                dto.Add(groupReceivingOrder);

            }

            return dto;
        }

        /// <summary>
        /// 提交按钮
        /// </summary>
        /// <returns></returns>
        public bool SubmitReceiving(out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                //创建表（如果不存在）
                sqlite.Database.EnsureCreated();

                var list = sqlite.SubmitReceiving.AsQueryable();
                if (list == null || !list.Any())
                {
                    message = "入库单未查询到数据";
                    return false;
                }

                List<GroupReceivingOrderDto> dto = new List<GroupReceivingOrderDto>();
                string ReceivingPoint = "";
                TCell cell = new TCell();
                int i = 1;
                int x = 1;
                string OrderSnDouble = "";
                string OrderSnThree = "";
                string cellCode = "";
                var materialLists = Context.TMaterial.AsQueryable();
                
                foreach (var order in list)//"68202312muzhi""67202312xiangjiao"
                {

                    GroupReceivingOrderDto groupReceivingOrder = new GroupReceivingOrderDto();
                    ChildrenReceivingOrder childrenReceivingOrder = new ChildrenReceivingOrder();
                    groupReceivingOrder.OrderSn = order.OrderSn;
                    childrenReceivingOrder.ReceivedQty = order.Qty;
                    childrenReceivingOrder.Position = order.Position;
                    string OrderSn = list.FirstOrDefault().OrderSn;
                    OrderSnDouble = order.OrderSn;
                    //
                    if (OrderSn != order.OrderSn && OrderSn != OrderSnDouble && OrderSnDouble != OrderSnThree)
                    {
                        x = 1;
                    }
                    cellCode = order.Position;
                    //var Treceiving1 = Context.TReceivingOrderDetails.FirstOrDefault(x => x.OrderSn == order.OrderSn);
                    var Treceiving1 = Context.TReceivingOrderDetails.AsNoTracking().AsQueryable();
                    Treceiving1 = Treceiving1.Where(x => x.OrderSn == order.OrderSn);

                    var Treceiving = OrderSn == order.OrderSn ?
                        Treceiving1.Skip((i - 1) * 1).Take(1).FirstOrDefault() :
                         Treceiving1.Skip((x - 1) * 1).Take(1).FirstOrDefault();
                    if (Treceiving == null)
                    {
                        tran.Rollback();
                        message = "入库单明细不存在!" + OrderSnDouble;
                        return false;
                    }
                    groupReceivingOrder.RelevanceOrderSn = Treceiving.RelevanceOrderSn;
                    groupReceivingOrder.BillType = Treceiving.BillType;
                    groupReceivingOrder.Agent = Treceiving.Agent;

                    groupReceivingOrder.SupplierId = Treceiving.SupplierId;
                    groupReceivingOrder.SupplierCode = Treceiving.SupplierCode;
                    groupReceivingOrder.SupplierName = Treceiving.SupplierName;
                    groupReceivingOrder.Contact = Treceiving.Contact;
                    groupReceivingOrder.ContactMobile = Treceiving.ContactMobile;
                    groupReceivingOrder.ProductDate = Treceiving.ProductDate;
                    groupReceivingOrder.Remark = Treceiving.Remark;
                    groupReceivingOrder.NowUserId = Treceiving.NowUserId;
                    groupReceivingOrder.NowUserName = Treceiving.NowUserRealName;
                    childrenReceivingOrder.Code = Treceiving.MaterialCode;
                    groupReceivingOrder.childrenReceivingOrders.Add(childrenReceivingOrder);
                    dto.Add(groupReceivingOrder);
                    i++;
                    x++;
                    //OrderSn = order.OrderSn;
                    OrderSnThree = order.OrderSn;

                    var InventoryList = Context.TInventories.Where(x => x.MaterialCode == Treceiving.MaterialCode);
                    if (InventoryList.Count() > 0)
                    {
                        var invenrotyPointList = InventoryList.Where(x => x.LocationCode == cellCode).ToList();
                        if (invenrotyPointList.Count() > 0)
                        {
                            invenrotyPointList.First().AvailableQty = invenrotyPointList.First().AvailableQty += order.Qty;

                            Context.Update(invenrotyPointList.First());

                        }
                        else
                        {
                            TInventory inventoryAddList = new TInventory();
                            var cellList = Context.TCells.Where(x => x.Code == cellCode).ToList();

                            if (cellList.Count() <= 0)
                            {
                                tran.Rollback();
                                message = "未查询到入库库位，请确认库位是否存在";
                                return false;
                            }
                            var materialList = materialLists.FirstOrDefault(x => x.Code == order.BarCode);
                            if (materialList == null)
                            {
                                continue;
                            }
                            inventoryAddList.LocationCode = cellCode;
                            inventoryAddList.LocationId = cellList.First().Id;
                            inventoryAddList.LocationName = cellList.First().Name;
                            inventoryAddList.LocationDepth = cellList.First().DepthIndex;
                            inventoryAddList.LocationLineNo = cellList.First().LineNo;
                            inventoryAddList.LocationLayerNo = cellList.First().LayerNo;
                            inventoryAddList.LocationColumnNo = cellList.First().ColumnNo;
                            inventoryAddList.Status = 1;
                            inventoryAddList.IsLock = false;
                            inventoryAddList.CreateDate = DateTime.Now;
                            inventoryAddList.MaterialId = materialList.Id;
                            inventoryAddList.MaterialCode = materialList.Code;
                            inventoryAddList.MaterialName = materialList.Name;
                            inventoryAddList.AvailableQty = order.Qty;
                            if (materialList.UnitId <= 0)
                            {
                                inventoryAddList.UnitId = 0;
                                inventoryAddList.UnitName = "";
                                inventoryAddList.QualityState = 1;
                            }
                            else
                            {
                                inventoryAddList.UnitId = materialList.UnitId;
                                inventoryAddList.UnitName = materialList.UnitName;
                                inventoryAddList.QualityState = 1;
                            }
                            inventoryAddList.UnitId = materialList.UnitId;
                            inventoryAddList.UnitName = materialList.UnitName;
                            inventoryAddList.InStockDate = DateTime.Now;
                            inventoryAddList.QualityState = materialList.QualityState;
                            inventoryAddList.MaterialCategoryId = materialList.MaterialCategoryId;
                            inventoryAddList.MaterialCategoryCode = materialList.MaterialCategoryCode;
                            inventoryAddList.MaterialCategoryName = materialList.MaterialCategoryName;
                            inventoryAddList.Price = materialList.Price;
                            inventoryAddList.ModelSpec = materialList.ModelSpec;
                            Context.TInventories.Add(inventoryAddList);
                            if (Context.SaveChanges() <= 0)
                            {
                                tran.Rollback();
                                message = "添加库存信息失败";
                                return false;
                            }

                        }
                    }
                    else
                    {
                        TInventory inventory1 = new TInventory();
                        var cellList = Context.TCells.Where(x => x.Code == cellCode).ToList();

                        if (cellList.Count() <= 0)
                        {
                            tran.Rollback();
                            message = "未查询到入库库位，请确认库位是否存在";
                            return false;
                        }
                        var materialList = Context.TMaterial.FirstOrDefault(x => x.Code == order.BarCode);
                        if (materialList == null)
                        {
                            continue;
                        }
                        inventory1.LocationCode = cellCode;
                        inventory1.LocationId = cellList.First().Id;
                        inventory1.LocationName = cellList.First().Name;
                        inventory1.LocationDepth = cellList.First().DepthIndex;
                        inventory1.LocationLineNo = cellList.First().LineNo;
                        inventory1.LocationLayerNo = cellList.First().LayerNo;
                        inventory1.LocationColumnNo = cellList.First().ColumnNo;
                        inventory1.Status = 1;
                        inventory1.IsLock = false;
                        inventory1.CreateDate = DateTime.Now;
                        inventory1.MaterialId = materialList.Id;
                        inventory1.MaterialCode = materialList.Code;
                        inventory1.MaterialName = materialList.Name;
                        inventory1.AvailableQty = order.Qty;
                        if (materialList.UnitId <= 0)
                        {
                            inventory1.UnitId = 0;
                            inventory1.UnitName = "";
                            inventory1.QualityState = 1;
                        }
                        else
                        {
                            inventory1.UnitId = materialList.UnitId;
                            inventory1.UnitName = materialList.UnitName;
                            inventory1.QualityState = 1;
                        }
                        //inventory1.UnitId = materialList.UnitId;
                        //inventory1.UnitName = materialList.UnitName;
                        inventory1.InStockDate = DateTime.Now;
                        inventory1.QualityState = materialList.QualityState;
                        inventory1.MaterialCategoryId = materialList.MaterialCategoryId;
                        inventory1.MaterialCategoryCode = materialList.MaterialCategoryCode;
                        inventory1.MaterialCategoryName = materialList.MaterialCategoryName;
                        inventory1.Price = materialList.Price;
                        inventory1.ModelSpec = materialList.ModelSpec;
                        Context.TInventories.Add(inventory1);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            message = "添加库存信息失败";
                            return false;
                        }
                    }


                    var existingOrder = sqlite.InboundListModes.FirstOrDefault(o => o.OrderSn == Treceiving.OrderSn);
                    //if (existingOrder != null && existingOrder.State == 4)
                    //{

                    //    sqlite.InboundListModes.Remove(existingOrder);
                    //    if (sqlite.SaveChanges() <= 0)
                    //    {
                    //        tran.Rollback();
                    //        message = "删除InboundListModes表数据失败!";
                    //        return false;
                    //    }
                    //}


                }

                decimal? qty = 0;

                foreach (var item in dto)
                {
                    foreach (var itemChild in item.childrenReceivingOrders)
                    {
                        //var inventoryList = Context.TInventories.Where(x => x.MaterialCode == itemChild.Code && x.LocationCode == itemChild.Position);
                        //if(inventoryList.Count() <= 0)
                        //{
                        //    TInventory inventory1 = new TInventory();
                        //    inventory1.LocationCode = itemChild.Position;
                        //    var locationList = Context.TCells.FirstOrDefault(x => x.Code == itemChild.Position);
                        //    if(locationList != null)
                        //    {
                        //        message = "未查询到仓位:" + itemChild.Position;
                        //        tran.Rollback();
                        //        return false;
                        //    }
                        //}

                        // 加库存
                        var TInventoryList = Context.TInventories.Where(x => x.MaterialCode == itemChild.Code).ToList();
                        TInventoryLog inventoryLog = new TInventoryLog();
                        inventoryLog.SourceType = 0;
                        inventoryLog.SourceSn = item.OrderSn;
                        string mes = "";


                        if (TInventoryList.Count() == 0)
                        {

                            if (!DoesItExistMaterial(item.OrderSn, cellCode, itemChild.Position, out mes))
                            {
                                tran.Rollback();
                                message = mes;
                                return false;
                            }
                        }

                        //var inventory = Context.TInventories.Where(x => x.MaterialCode == itemChild.Code).ToList()[0];
                        var inventory = Context.TInventories.Where(x => x.MaterialCode == itemChild.Code && x.LocationCode == itemChild.Position).ToList();
                        if (inventory.Count() > 0)
                        {

                            TInventory inventory1 = inventory[0];
                            inventoryLog.WarehouseId = inventory1.WarehouseId;
                            inventoryLog.WarehouseName = inventory1.WarehouseName;
                            inventoryLog.LocationCode = itemChild.Position;
                            inventoryLog.PalletBarcode = inventory1.PalletBarcode;
                            inventoryLog.MaterialId = inventory1.MaterialId;
                            inventoryLog.MaterialCode = inventory1.MaterialCode;
                            inventoryLog.MaterialName = inventory1.MaterialName;
                            inventoryLog.BaseUnitId = inventory1.UnitId;
                            inventoryLog.BaseUnitName = inventory1.UnitName;
                            //原始数量
                            inventoryLog.StartQty = inventory1.AvailableQty == null ? 0 : inventory1.AvailableQty - itemChild.ReceivedQty;
                            qty = inventory1.AvailableQty == null ? 0 : inventory1.AvailableQty - itemChild.ReceivedQty;
                            //变更数量
                            inventoryLog.ChangeQty = itemChild.ReceivedQty;
                            //最终数量
                            inventoryLog.EndQty = qty + itemChild.ReceivedQty;
                            inventoryLog.CreateDate = DateTime.Now;
                            inventoryLog.CreateUserId = item.CreateUserId;
                            inventoryLog.CreateUser = item.CreateUserName;
                            Context.TInventoryLogs.Add(inventoryLog);
                        }
                      
                        var ReceivingOrderDetailList = Context.TReceivingOrderDetails.Where(x => x.OrderSn == item.OrderSn).ToList();

                        IsInventoryWarn(TInventoryList);

                        foreach (var ReceivingOrderDetail in ReceivingOrderDetailList)
                        {
                            ReceivingOrderDetail.Status = 3;
                            Context.TReceivingOrderDetails.Update(ReceivingOrderDetail);
                        }

                        var submitReceivingList = sqlite.SubmitReceiving.Where(x => x.OrderSn == item.OrderSn).ToList();
                        sqlite.SubmitReceiving.RemoveRange(submitReceivingList);
                        var queryReceivingList = sqlite.RecevingQueryTable.Where(x => x.OrderSn == item.OrderSn).ToList();
                        sqlite.RecevingQueryTable.RemoveRange(queryReceivingList);
                        var receibingModesList = sqlite.InboundListModes.Where(x => x.OrderSn == item.OrderSn).ToList();
                        sqlite.InboundListModes.RemoveRange(receibingModesList);

                    }

                }

                if (sqlite.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "入库数据修改失败!";
                    return false;
                }
                if (Context.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "入库增加库存失败！";
                    return false;
                }
                tran.Commit();
                message = "入库增加库存成功！";
                return true;

            }
            catch
            {
                tran.Rollback();
                message = "入库库存修改失败!";
                return false;
            }


        }

        /// <summary>
        /// 封装方法
        /// </summary>
        /// <param name="inventories"></param>
        /// <returns></returns>
        public bool IsInventoryWarn(List<TInventory> inventories)
        {
            try
            {
                var WarningRolesList = Context.TWarningRules.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                if (WarningRolesList == null || WarningRolesList.Count() <= 0)
                {
                    return false;
                }

                if (inventories[0].AvailableQty > WarningRolesList.First().WarningQtyMax)
                {
                    var InventoryWarn = Context.TInventoryWarn.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                    if (InventoryWarn == null || InventoryWarn.Count() <= 0)
                    {
                        TInventoryWarn inventoryWarnModel = new TInventoryWarn();
                        inventoryWarnModel.MaterialId = inventories[0].MaterialId;
                        inventoryWarnModel.MaterialCode = inventories[0].MaterialCode;
                        inventoryWarnModel.MaterialName = inventories[0].MaterialName;
                        inventoryWarnModel.MaterialTypeName = inventories[0].MaterialTypeName;
                        inventoryWarnModel.WarnType = 2;
                        inventoryWarnModel.QTY = inventories[0].AvailableQty;
                        Context.TInventoryWarn.Add(inventoryWarnModel);
                    }
                    else
                    {
                        //InventoryWarn.First().MaterialId = inventories[0].MaterialId;
                        //InventoryWarn.First().MaterialCode = inventories[0].MaterialCode;
                        //InventoryWarn.First().MaterialName = inventories[0].MaterialName;
                        //InventoryWarn.First().MaterialTypeName = inventories[0].MaterialTypeName;
                        InventoryWarn.First().QTY = inventories[0].AvailableQty;
                        InventoryWarn.First().WarnType = 2;
                        Context.TInventoryWarn.Update(InventoryWarn.First());
                    }
                    if (Context.SaveChanges() <= 0)
                    {
                        return false;
                    }

                }
                else if (inventories[0].AvailableQty < WarningRolesList.First().WarningQtyMax && inventories[0].AvailableQty > WarningRolesList.First().WarningQtyMin)
                {
                    var InventoryWarn = Context.TInventoryWarn.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                    if (InventoryWarn != null || InventoryWarn.Count() <= 0)
                    {
                        Context.TInventoryWarn.Remove(InventoryWarn.First());
                    }
                    if (Context.SaveChanges() <= 0)
                    {
                        return false;
                    }
                }
                else if (inventories[0].AvailableQty < WarningRolesList.First().WarningQtyMin)
                {
                    var InventoryWarn = Context.TInventoryWarn.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                    if (InventoryWarn == null || InventoryWarn.Count() <= 0)
                    {
                        TInventoryWarn inventoryWarnModel = new TInventoryWarn();
                        inventoryWarnModel.MaterialId = inventories[0].MaterialId;
                        inventoryWarnModel.MaterialCode = inventories[0].MaterialCode;
                        inventoryWarnModel.MaterialName = inventories[0].MaterialName;
                        inventoryWarnModel.MaterialTypeName = inventories[0].MaterialTypeName;
                        inventoryWarnModel.WarnType = 1;
                        inventoryWarnModel.QTY = inventories[0].AvailableQty;
                        Context.TInventoryWarn.Add(inventoryWarnModel);
                    }
                    else
                    {
                        foreach (var item in InventoryWarn)
                        {
                            //item.MaterialId = inventories[0].MaterialId;
                            //item.MaterialCode = inventories[0].MaterialCode;
                            //item.MaterialName = inventories[0].MaterialName;
                            //item.MaterialTypeName = inventories[0].MaterialTypeName;
                            item.QTY = inventories[0].AvailableQty;
                            Context.TInventoryWarn.Update(item);
                        }

                    }
                    if (Context.SaveChanges() <= 0)
                    {
                        return false;
                    }
                }


                return true;
            }
            catch
            {
                return false;
            }

        }

        public List<TUser> GetPurchaseRole()
        {
            try
            {
                var roleList = Context.TRoles.FirstOrDefault(x => x.RoleCode == "caigou");
                var userRoleList = Context.TUserRoles.Where(x => x.RoleId == roleList.Id).ToList();
                List<TUser> users = new List<TUser>();
                foreach (var user in userRoleList)
                {
                    var userOne = Context.TUsers.FirstOrDefault(x => x.Id == user.UserId);
                    users.Add(userOne);
                }

                return users;
            }
            catch
            {
                return null;
            }

        }


        #region 添加入库单弃用
        ///// <summary>
        ///// 添加入库单管理
        ///// </summary>
        ///// <param name="m"></param>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //public bool AddTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        //{
        //    message = "";
        //    using (var tran = Context.Database.BeginTransaction())
        //        try
        //        {
        //            //货主信息
        //            if (m.OwnerId.HasValue)
        //            {
        //                var depobj = Context.TDepartments.AsQueryable();
        //                var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
        //                var owobj = Context.TOwners.Where(x=>x.Status==1);
        //                var delist = (from d in depobj
        //                              join de in depowobj
        //                              on d.Id equals de.DepartmentId
        //                              join o in owobj
        //                              on de.OwnerId equals o.Id
        //                              select d).FirstOrDefault();
        //                if (delist != null)
        //                {
        //                    m.DeptCode = delist.DepartmentCode;
        //                    m.DeptName = delist.DepartmentName;
        //                    var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
        //                    if (owerobj != null)
        //                    {
        //                        m.OwnerName = owerobj.Name;
        //                    }
        //                }
        //                else
        //                {
        //                    message = "货主不存在或已被禁用，请先维护";
        //                    return false;
        //                }
        //            }
        //            else
        //            {
        //                m.OwnerId = 0;
        //                m.OwnerName = "";
        //                m.DeptCode = "";
        //                m.DeptName = "";
        //            }

        //            //库房信息
        //            var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
        //            if (warehouseobj != null && warehouseobj.Status==1)
        //            {
        //                m.WarehouseName = warehouseobj.Name;
        //                m.WarehouseCode = warehouseobj.Code;
        //            }
        //            else
        //            {
        //                message = "仓库不存在或仓库已被禁用，请先维护";
        //                return false;
        //            }
        //            //供应商信息
        //            var supplierobj = Context.TSuppliers.Find(m.SupplierId);
        //            if (supplierobj != null)
        //            {
        //                m.SupplierName = supplierobj.Name;
        //            }
        //            //物料信息
        //            var materialobj = Context.TMaterials.Find(m.MaterialId);
        //            if (materialobj != null)
        //            {
        //                m.MaterialCode = materialobj.Code;
        //                m.MaterialImg = materialobj.Img;
        //                m.MaterialName = materialobj.Name;
        //                m.UnitId = materialobj.UnitId;
        //                m.UnitName = materialobj.UnitName;
        //                m.MaterialTypeCode = materialobj.TypeCode;
        //                m.MaterialTypeName = materialobj.TypeName;
        //                if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
        //                {
        //                    m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
        //                }
        //            }
        //            //物料批次
        //            TMaterialKey materialKey = null;
        //            var materkeyobj = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
        //            if (materkeyobj != null)
        //            {
        //                materialKey = materkeyobj;
        //            }
        //            //逻辑分区
        //            var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
        //            if (dicobj != null)
        //            {
        //                m.LogicalPartName = dicobj.ItemName;
        //            }
        //            //订单来源默认手动创建
        //            m.SourceType = 0;
        //            //质检状态默认为合格
        //            m.QualityState = 1;
        //            m.ReceivedQty = 0;
        //            m.PackagedQty = 0;
        //            m.PackQty = 0;

        //            #region 审计字段
        //            m.CreateUserId = m.NowUserId;
        //            m.CreateUserName = m.NowUserRealName;
        //            m.CreateDate = DateTime.Now;
        //            m.ModifyUserId = m.NowUserId;
        //            m.ModifyUserName = m.NowUserRealName;
        //            m.ModifyDate = DateTime.Now;
        //            m.AuditUserId = m.NowUserId;
        //            m.AuditUserName = m.NowUserRealName;
        //            m.AuditDate = DateTime.Now;
        //            m.SubmitUserId = m.NowUserId;
        //            m.SubmitUserName = m.NowUserRealName;
        //            m.SubmitDate = DateTime.Now;
        //            #endregion
        //            //采购订单行项目类型
        //            m.PurOrderLineType = 0;
        //            m.StackedQty = 0;
        //            if (materialKey == null)
        //            {
        //                TMaterialKey materkeyinsert = new TMaterialKey();
        //                materkeyinsert.BatchNo = m.BatchNo;
        //                materkeyinsert.MaterialId = m.MaterialId;
        //                materkeyinsert.OutFactoryDate = m.OutFactoryDate;
        //                materkeyinsert.OwnerId = m.OwnerId;
        //                materkeyinsert.OwnerName = m.OwnerName;
        //                materkeyinsert.ProduceFactory = m.ProduceFactory;
        //                materkeyinsert.ProductDate = m.ProductDate;
        //                materkeyinsert.Qadate = m.Qadate;
        //                materkeyinsert.SupplierName = m.SupplierName;
        //                materkeyinsert.SupplierId = m.SupplierId;
        //                materkeyinsert.ExpireDate = m.ExpireDate;
        //                materkeyinsert.CreateDate = DateTime.Now;
        //                materkeyinsert.MaterialCode = m.MaterialCode;
        //                materkeyinsert.MaterialName = m.MaterialName;
        //                materkeyinsert.QualityState = m.QualityState;
        //                materkeyinsert.DeptCode = m.DeptCode;
        //                materkeyinsert.DeptName = m.DeptName;
        //                materkeyinsert.Mblnr = m.Mblnr;
        //                materkeyinsert.Mjahr = m.Mjahr;
        //                materkeyinsert.Zeile = m.Zeile;
        //                materkeyinsert.ContractNo = m.ContractNo;
        //                materkeyinsert.PurOrderNo = m.PurOrderNo;
        //                materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
        //                materkeyinsert.PurOrderLineType = m.PurOrderLineType;
        //                materkeyinsert.ProOrderNo = m.ProOrderNo;
        //                materkeyinsert.OutOrderNo = m.OutOrderNo;
        //                Context.TMaterialKeys.Add(materkeyinsert);
        //                int result = Context.SaveChanges();
        //                if (result == 0)
        //                {
        //                    message = "保存失败！";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //                m.MaterialKeyId = materkeyinsert.Id;
        //            }
        //            else
        //            {
        //                m.MaterialKeyId = materialKey.Id;
        //                var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
        //                if (materkey != null)
        //                {
        //                    materkey.BatchNo = m.BatchNo;
        //                    materkey.OutFactoryDate = m.OutFactoryDate;
        //                    materkey.OwnerId = m.OwnerId;
        //                    materkey.OwnerName = m.OwnerName;
        //                    materkey.ProduceFactory = m.ProduceFactory;
        //                    materkey.ProductDate = m.ProductDate;
        //                    materkey.Qadate = m.Qadate;
        //                    materkey.SupplierId = m.SupplierId;
        //                    materkey.SupplierName = m.SupplierName;
        //                    materkey.ExpireDate = m.ExpireDate;
        //                    materkey.MaterialCode = m.MaterialCode;
        //                    materkey.MaterialName = m.MaterialName;
        //                    materkey.QualityState = m.QualityState;
        //                    materkey.DeptCode = m.DeptCode;
        //                    materkey.DeptName = m.DeptName;
        //                    materkey.Mblnr = m.Mblnr;
        //                    materkey.Mjahr = m.Mjahr;
        //                    materkey.Zeile = m.Zeile;
        //                    materkey.ContractNo = m.ContractNo;
        //                    materkey.ProOrderNo = m.ProOrderNo;
        //                    materkey.PurOrderLineNo = m.PurOrderLineNo;
        //                    materkey.PurOrderLineType = m.PurOrderLineType;
        //                    materkey.ProOrderNo = m.ProOrderNo;
        //                    materkey.OutOrderNo = m.OutOrderNo;
        //                    Context.TMaterialKeys.Update(materkey);
        //                }
        //                int result = Context.SaveChanges();
        //                if (result <= 0)
        //                {
        //                    message = "保存失败！";
        //                    tran.Rollback();
        //                    return false;
        //                }
        //            }
        //            Context.TReceivingOrderDetails.Add(m);
        //            int resultt = Context.SaveChanges();
        //            if (resultt > 0)
        //            {
        //                tran.Commit();
        //                return true;
        //            }
        //            tran.Rollback();
        //            return false;

        //        }
        //        catch (Exception)
        //        {
        //            tran.Rollback();
        //            throw;
        //        }
        //}
        #endregion

        #region 修改入库单弃用
        ///// <summary>
        ///// 修改入库单弃用
        ///// </summary>
        ///// <param name="m"></param>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //public bool UpdTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        //{
        //message = "";
        //using (var tran = Context.Database.BeginTransaction())
        //    try
        //    {
        //        //货主信息
        //        if (m.OwnerId.HasValue)
        //        {
        //            var depobj = Context.TDepartments.AsQueryable();
        //            var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
        //            var delist = (from d in depobj
        //                          join de in depowobj
        //                          on d.Id equals de.DepartmentId                                   
        //                          select d).FirstOrDefault();
        //            if (delist != null)
        //            {
        //                m.DeptCode = delist.DepartmentCode;
        //                m.DeptName = delist.DepartmentName;                         
        //            }
        //            else
        //            {
        //                message = "货主不存在或已被禁用，请先维护";
        //                return false;
        //            }
        //        }
        //        else
        //        {
        //            m.OwnerId = 0;
        //            m.OwnerName = "";
        //            m.DeptCode = "";
        //            m.DeptName = "";
        //        }

        //        //库房信息
        //        var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
        //        if (warehouseobj != null && warehouseobj.Status==1)
        //        {
        //            m.WarehouseName = warehouseobj.Name;
        //            m.WarehouseCode = warehouseobj.Code;
        //        }
        //        else
        //        {
        //            message = "仓库不存在或仓库已被禁用，请先维护";
        //            return false;
        //        }

        //        //TReceivingOrderDetail oldData = null;
        //        //var olddataobj = Context.TReceivingOrderDetails.Find(m.Id);
        //        //if (olddataobj == null) 
        //        //{
        //        //    message = "当前数据可能已被删除，请刷新后再试";
        //        //    return false;
        //        //}
        //        //else
        //        //{
        //        //    if(olddataobj.Status!=0)
        //        //    {
        //        //        message = "只有状态为创建的入库单才能修改";
        //        //        return false;
        //        //    }
        //        //    oldData = olddataobj;
        //        //}
        //        //oldData = olddataobj;
        //        //供应商信息
        //        var supplierobj = Context.TSuppliers.Find(m.SupplierId);
        //        if (supplierobj != null)
        //        {
        //            m.SupplierName = supplierobj.Name;
        //        }
        //        //物料信息
        //        var materialobj = Context.TMaterials.Find(m.MaterialId);
        //        if (materialobj != null)
        //        {
        //            m.MaterialCode = materialobj.Code;
        //            m.MaterialImg = materialobj.Img;
        //            m.MaterialName = materialobj.Name;
        //            m.UnitId = materialobj.UnitId;
        //            m.UnitName = materialobj.UnitName;
        //            m.MaterialTypeCode = materialobj.TypeCode;
        //            m.MaterialTypeName = materialobj.TypeName;
        //            if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
        //            {
        //                m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
        //            }
        //        }
        //        //物料批次
        //        TMaterialKey materialKey = null;
        //        var materkeyobj = Context.TMaterialKeys.Find(m.MaterialKeyId);
        //        if (materkeyobj == null)
        //        {                     
        //            var materkeyobj2 = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
        //            if(materkeyobj2!=null)
        //            {
        //                materialKey = materkeyobj2;
        //            }
        //        }
        //        else
        //        {
        //            materialKey = materkeyobj;
        //        }
        //        //逻辑分区
        //        var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
        //        if (dicobj != null)
        //        {
        //            m.LogicalPartName = dicobj.ItemName;
        //        }                

        //        #region 审计字段
        //        m.ModifyUserId = m.NowUserId;
        //        m.ModifyUserName = m.NowUserRealName;
        //        m.ModifyDate = DateTime.Now;
        //        m.AuditUserId = m.NowUserId;
        //        m.AuditUserName = m.NowUserRealName;
        //        m.AuditDate = DateTime.Now;
        //        #endregion                
        //        if (materialKey == null)
        //        {
        //            TMaterialKey materkeyinsert = new TMaterialKey();
        //            materkeyinsert.BatchNo = m.BatchNo;
        //            materkeyinsert.MaterialId = m.MaterialId;
        //            materkeyinsert.OutFactoryDate = m.OutFactoryDate;
        //            materkeyinsert.OwnerId = m.OwnerId;
        //            materkeyinsert.OwnerName = m.OwnerName;
        //            materkeyinsert.ProduceFactory = m.ProduceFactory;
        //            materkeyinsert.ProductDate = m.ProductDate;
        //            materkeyinsert.Qadate = m.Qadate;
        //            materkeyinsert.SupplierName = m.SupplierName;
        //            materkeyinsert.SupplierId = m.SupplierId;
        //            materkeyinsert.ExpireDate = m.ExpireDate;
        //            materkeyinsert.CreateDate = DateTime.Now;
        //            materkeyinsert.MaterialCode = m.MaterialCode;
        //            materkeyinsert.MaterialName = m.MaterialName;
        //            materkeyinsert.QualityState = m.QualityState;
        //            materkeyinsert.DeptCode = m.DeptCode;
        //            materkeyinsert.DeptName = m.DeptName;
        //            materkeyinsert.Mblnr = m.Mblnr;
        //            materkeyinsert.Mjahr = m.Mjahr;
        //            materkeyinsert.Zeile = m.Zeile;
        //            materkeyinsert.ContractNo = m.ContractNo;
        //            materkeyinsert.PurOrderNo = m.PurOrderNo;
        //            materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
        //            materkeyinsert.PurOrderLineType = m.PurOrderLineType;
        //            materkeyinsert.ProOrderNo = m.ProOrderNo;
        //            materkeyinsert.OutOrderNo = m.OutOrderNo;
        //            Context.TMaterialKeys.Add(materkeyinsert);
        //            int result = Context.SaveChanges();
        //            if (result == 0)
        //            {
        //                message = "保存失败！";
        //                tran.Rollback();
        //                return false;
        //            }
        //            m.MaterialKeyId = materkeyinsert.Id;
        //        }
        //        else
        //        {
        //            m.MaterialKeyId = materialKey.Id;
        //            var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
        //            if (materkey != null)
        //            {
        //                materkey.BatchNo = m.BatchNo;
        //                materkey.OutFactoryDate = m.OutFactoryDate;
        //                materkey.OwnerId = m.OwnerId;
        //                materkey.OwnerName = m.OwnerName;
        //                materkey.ProduceFactory = m.ProduceFactory;
        //                materkey.ProductDate = m.ProductDate;
        //                materkey.Qadate = m.Qadate;
        //                materkey.SupplierId = m.SupplierId;
        //                materkey.SupplierName = m.SupplierName;
        //                materkey.ExpireDate = m.ExpireDate;
        //                materkey.MaterialCode = m.MaterialCode;
        //                materkey.MaterialName = m.MaterialName;
        //                materkey.QualityState = m.QualityState;
        //                materkey.DeptCode = m.DeptCode;
        //                materkey.DeptName = m.DeptName;
        //                materkey.Mblnr = m.Mblnr;
        //                materkey.Mjahr = m.Mjahr;
        //                materkey.Zeile = m.Zeile;
        //                materkey.ContractNo = m.ContractNo;
        //                materkey.ProOrderNo = m.ProOrderNo;
        //                materkey.PurOrderLineNo = m.PurOrderLineNo;
        //                materkey.PurOrderLineType = m.PurOrderLineType;
        //                materkey.ProOrderNo = m.ProOrderNo;
        //                materkey.OutOrderNo = m.OutOrderNo;
        //                Context.TMaterialKeys.Update(materkey);
        //            }
        //            int result = Context.SaveChanges();
        //            if (result <= 0)
        //            {
        //                message = "保存失败！";
        //                tran.Rollback();
        //                return false;
        //            }
        //        }
        //        Context.TReceivingOrderDetails.Update(m);
        //        int resultt = Context.SaveChanges();
        //        if (resultt > 0)
        //        {
        //            tran.Commit();
        //            return true;
        //        }
        //        tran.Rollback();
        //        return false;

        //    }
        //    catch (Exception)
        //    {
        //        tran.Rollback();
        //        throw;
        //    }
        //message = "";
        //return false;
        //}
        #endregion

        /// <summary>
        /// 删除入库单
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        public bool DelTReceivingOrderDetail(string ordersn)
        {
            var sobj = Context.TReceivingOrderDetails.AsNoTracking().Where(x => x.OrderSn == ordersn);
            if (sobj.Any())
            {
                Context.TReceivingOrderDetails.RemoveRange(sobj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 显示入库单 弃用
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="status"></param>
        /// <param name="warehouseid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TReceivingOrderDetail> GetReceivingOrderDetailList(string orderSn, int billType, int status, int warehouseid, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingOrderDetails.AsQueryable();
            //入库单号
            if (!string.IsNullOrEmpty(orderSn))
            {
                list = list.Where(x => x.OrderSn.Contains(orderSn));
            }

            if (billType != 0)
            {
                list = list.Where(x => x.BillType == billType);
            }

            if (status < 8)
            {
                list = list.Where(x => x.Status == status);
            }

            if (warehouseid != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseid);
            }

            totalCount = list.Count();

            list = list.OrderByDescending(x => x.CreateDate);

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TReceivingOrderDetail GetTReceivingOrderDetailById(int rid)
        {
            return Context.TReceivingOrderDetails.Find(rid);
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdTReceivingOrderDetaState(ReceivingOrderDetailDto m)
        {
            var rlist = Context.TReceivingOrderDetails.AsNoTracking().Where(x => x.OrderSn == m.OrderSN);

            if (rlist.Any())
            {
                foreach (var item in rlist)
                {
                    item.AuditUserId = m.NowUserId;
                    item.AuditUserName = m.NowUserRealName;
                    item.AuditDate = DateTime.Now;
                    item.Remark = m.Remark;
                    //修改为：作业中
                    item.Status = 2;
                    Context.TReceivingOrderDetails.Update(item);
                    TAuditRecord auditRecord = new TAuditRecord();
                    //记录类型：入库单审核
                    auditRecord.RecordType = 1;
                    auditRecord.AuditUserId = m.NowUserId;
                    auditRecord.AuditUserName = m.NowUserName;
                    auditRecord.AuditUserRealName = m.NowUserRealName;
                    Context.TAuditRecords.Add(auditRecord);
                }
                //switch (robj.Status)
                //{
                //    case 0:
                //        robj.AuditUserId = m.NowUserId;
                //        robj.AuditUserName = m.NowUserRealName;
                //        robj.AuditDate = DateTime.Now;
                //        robj.Remark = m.Remark;
                //        //修改为：作业中
                //        robj.Status = 2;
                //        Context.TReceivingOrderDetails.Update(robj);
                //        TAuditRecord auditRecord = new TAuditRecord();
                //        //记录类型：入库单审核
                //        auditRecord.RecordType = 1;
                //        auditRecord.AuditUserId = m.NowUserId;
                //        auditRecord.AuditUserName = m.NowUserName;
                //        auditRecord.AuditUserRealName = m.NowUserRealName;
                //        Context.TAuditRecords.Add(auditRecord);
                //        break;
                //    case 1:
                //        break;

                //    case 2:
                //        robj.ModifyUserId = m.NowUserId;
                //        robj.ModifyUserName = m.NowUserRealName;
                //        robj.ModifyDate = DateTime.Now;
                //        //修改为：作业中
                //        robj.Status = 3;
                //        Context.TReceivingOrderDetails.Update(robj);
                //        break;

                //    case 3:
                //        robj.ModifyUserId = m.NowUserId;
                //        robj.ModifyUserName = m.NowUserRealName;
                //        robj.ModifyDate = DateTime.Now;
                //        //修改为：已完成
                //        robj.Status = 4;
                //        Context.TReceivingOrderDetails.Update(robj);
                //        break;

                //    default:
                //        break;
                //}
                return Context.SaveChanges() > 0;
            }
            return false;
        }
        /// <summary>
        /// 导出入库单
        /// </summary>
        /// <returns></returns>
        public List<TReceivingOrderDetail> GetTReceivingOrderDetailExcel()
        {
            try
            {
                return Context.TReceivingOrderDetails.AsQueryable().ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 执行入库作业
        /// </summary>
        /// <returns></returns>
        public bool ExecReceving(TReceivingOrderDetail detail, out string errMsg)
        {

            errMsg = string.Empty;
            TReceivingOrderDetail? orderDetail = detail;

            if (orderDetail.Status != (int)EmBillStatus.Pass)
            {
                // throw new Exception("入库单不存在");
                errMsg = "入库单未审核通过";
                return false;
            }

            orderDetail.Status = (int)EmBillStatus.Executing;
            orderDetail.ModifyDate = DateTime.Now;
            // orderDetail.ModifyUserId = 0;
            // orderDetail.ModifyUserName = "";

            bool result = base.Upd(orderDetail);

            return result;
        }

        /// <summary>
        /// 入库单列表显示
        /// </summary>
        /// <param name="orderSn"></param>
        /// <param name="billType"></param>
        /// <param name="status"></param>
        /// <param name="warehouseid"></param>
        /// <param name="rolecode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<GroupReceivingOrderDto> GetGroupReceivingOrderList(string? StartTime, string? EndTime, int? billType, int? status, string rolecode, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingOrderDetails.AsQueryable();
            if (StartTime != null && EndTime != null)
            {
                string StartdateString = StartTime;
                DateTime Startdate = DateTime.Parse(StartdateString);
                string EnddateString = EndTime;
                DateTime Enddate = DateTime.Parse(EnddateString);
                list = list.Where(x => x.CreateDate >= Startdate && x.CreateDate <= Enddate);

            }

            if (billType != 0)
            {
                list = list.Where(x => x.BillType == billType);
            }

            if (status < 8)
            {
                list = list.Where(x => x.Status == status);
            }

            bool Examine = false;
            if (!string.IsNullOrEmpty(rolecode) && rolecode == "admin")
                Examine = true;
            var groupreceivinglist = new List<GroupReceivingOrderDto>();
            groupreceivinglist = list.GroupBy(x => x.OrderSn)
                .Select(r => new GroupReceivingOrderDto
                {
                    OrderSn = r.Key,
                    BillType = r.FirstOrDefault().BillType,
                    SupplierName = r.FirstOrDefault().SupplierName,
                    Remark = r.FirstOrDefault().Remark,
                    ExamineState = Examine,
                    State = r.FirstOrDefault().Status,
                    ProductDate = r.FirstOrDefault().ProductDate,
                    Agent = r.FirstOrDefault().Agent,
                }).ToList();
            totalCount = groupreceivinglist.Count();

            groupreceivinglist = groupreceivinglist.AsEnumerable()
                .OrderByDescending(dto => dto.ProductDate)
                .Skip((pageIndex - 1) * pageSize).Take(pageSize)
                .ToList();


            return groupreceivinglist;
        }



        /// <summary>
        /// 添加入库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddTReceivingOrderDetail(GroupReceivingOrderDto m, out string message)
        {
            message = "";
            //判断当前供应商是否存在
            var suppobj = Context.TSuppliers.AsNoTracking().FirstOrDefault(x => x.Code == m.SupplierCode);
            //if (suppobj != null)
            //{
            //    m.SupplierId = suppobj.Id;
            //    m.SupplierName = suppobj.Name;
            //    //修改已有的
            //    suppobj.Name = m.SupplierName;
            //    suppobj.Contact = m.Contact;
            //    suppobj.ContactMobile = m.ContactMobile;
            //    suppobj.ModifyDate = DateTime.Now;
            //    suppobj.ModifyUserId = m.NowUserId;
            //    suppobj.ModifyUserName = m.NowUserName;
            //    Context.TSuppliers.Update(suppobj);
            //}
            //else
            //{
            //    TSupplier supplier = new TSupplier();
            //    supplier.Code = m.SupplierCode;
            //    supplier.Name = m.SupplierName;
            //    supplier.Contact = m.Contact;
            //    supplier.ContactMobile = m.ContactMobile;
            //    supplier.CreateDate = DateTime.Now;
            //    supplier.CreateUserId = m.NowUserId;
            //    supplier.CreateUserName = m.NowUserName;
            //    Context.TSuppliers.Add(supplier);
            //}

            foreach (var item in m.File)
            {
                TReceivingOrderDetailFile receivingOrderDetailFile = new()
                {
                    ReceivingOrderSn = m.OrderSn,
                    FileUrl = item.url,
                    FileName = item.name
                };
                Context.TReceivingOrderDetailFile.Add(receivingOrderDetailFile);

            }
            //添加入库凭证

            foreach (var item in m.childrenReceivingOrders)
            {
                //if (item.MaterialNameStatus == 0)
                //{
                //    var MaterialList = Context.TMaterial.Where(x => x.Name == item.Name);
                //}
                TReceivingOrderDetail receivingOrderDetail = new TReceivingOrderDetail();
                receivingOrderDetail.OrderSn = m.OrderSn;
                receivingOrderDetail.BillType = m.BillType;
                receivingOrderDetail.RelevanceOrderSn = m.RelevanceOrderSn;
                receivingOrderDetail.Agent = m.Agent;
                //receivingOrderDetail.SupplierId = m.SupplierId;
                //receivingOrderDetail.SupplierCode = m.SupplierCode;
                //receivingOrderDetail.SupplierName = m.SupplierName;
                //receivingOrderDetail.Contact = m.Contact;                                                     
                //receivingOrderDetail.ContactMobile = m.ContactMobile;
                receivingOrderDetail.ProductDate = DateTime.Now;
                receivingOrderDetail.MaterialCategoryId = item.MakerialCategoryId;
                receivingOrderDetail.UnitId = item.UnitId;
                receivingOrderDetail.UnitName = item.UnitName;
                //if (item.UnitId != null && item.UnitId > 0)
                //{
                //    var unitobj = Context.TDictItems.Find(item.UnitId);
                //    if (unitobj != null)
                //    {
                //        receivingOrderDetail.UnitId = unitobj.Id;
                //        receivingOrderDetail.UnitName = unitobj.ItemName;
                //    }
                //}
                //装备名称
                receivingOrderDetail.MaterialCategoryName = item.MaterialCategoryName;
                receivingOrderDetail.MaterialId = item.MaterialId;
                receivingOrderDetail.MaterialName = item.Name;
                receivingOrderDetail.MaterialCode = item.Code;
                receivingOrderDetail.MaterialGroupId = item.MaterialGroupCode;
                receivingOrderDetail.ModelSpec = item.ModelSpec;
                receivingOrderDetail.QualityState = item.QualityState;//质量等级
                if(item.QualityState == 0)
                {
                    receivingOrderDetail.QualityStateName = "新品";
                }
                else if(item.QualityState == 1)
                {
                    receivingOrderDetail.QualityStateName = "堪用品";
                }else if(item.QualityState == 2)
                {
                    receivingOrderDetail.QualityStateName = "待修品";
                }
                else
                {
                    receivingOrderDetail.QualityStateName = "废品";
                }
                receivingOrderDetail.ReceivedQty = item.ReceivedQty;
                receivingOrderDetail.Qty = item.ReceivedQty;
                receivingOrderDetail.TotalPrice = item.TotalPrice;
                receivingOrderDetail.Price = item.Price;
                receivingOrderDetail.Remark = m.Remark;
                receivingOrderDetail.Position = item.Position;
                if (suppobj == null)
                {
                    TSupplier supplier = new TSupplier();
                    supplier.Code = "DR" + m.SupplierCode;
                    supplier.Name = m.SupplierName;
                    supplier.Contact = m.Contact;
                    supplier.Contact1Mobile = m.ContactMobile;
                    supplier.CreateDate = DateTime.Now;
                    supplier.CreateUserId = m.CreateUserId;
                    supplier.CreateUserName = m.CreateUserName;
                    Context.TSuppliers.Add(supplier);
                    if (Context.SaveChanges() <= 0)
                    {
                        message = "供应商添加失败";
                        return false;
                    }
                }
                receivingOrderDetail.SupplierId = m.SupplierId;
                receivingOrderDetail.SupplierName = m.SupplierName;
                receivingOrderDetail.SupplierCode = m.SupplierCode;
                receivingOrderDetail.Contact = m.Contact;
                receivingOrderDetail.ContactMobile = m.ContactMobile;

                //订单来源默认手动创建
                receivingOrderDetail.SourceType = 0;

                //var receivingList = Context.TReceivingOrderDetails.Where(x => x.MaterialCode == item.Code);
                //foreach( var receiving in receivingList )
                //{
                //    if(receiving.UnitName != item.UnitName)
                //    {
                //        message = "物料" + item.Name + "与库存中物料计量单位不一致，库存中计量单位为" + receiving.UnitName;
                //        return false;
                //    }
                //}

                #region 审计字段
                receivingOrderDetail.CreateUserId = m.NowUserId;
                receivingOrderDetail.CreateUserName = m.NowUserName;
                receivingOrderDetail.CreateDate = DateTime.Now;
                #endregion
                Context.TReceivingOrderDetails.Add(receivingOrderDetail);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 根据入库单编号查询信息
        /// </summary>
        /// <param name="ordersn"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public GroupReceivingOrderDto GetGroupReceivingOrderDtoByOrdersn(string ordersn)
        {
            if(ordersn.Substring(0, 1).Contains("C"))
            {
                GroupReceivingOrderDto groupReceivingOrderDto = new GroupReceivingOrderDto();
                var shippingList = Context.TShippingOrderDetails.FirstOrDefault(x => x.OrderSn == ordersn);
                var shippingLockList = Context.TShippingLockCells.Where(x => x.OrderDetailId == shippingList.Id);
                //主表赋值待定
                foreach (var shippingLock in shippingLockList)
                {
                    ChildrenReceivingOrder childrenReceiving = new ChildrenReceivingOrder();
                    childrenReceiving.Id = shippingLock.Id;
                    childrenReceiving.MakerialCategoryId = shippingLock.MaterialCategoryId;
                    childrenReceiving.MaterialCategoryName = shippingLock.MaterialCategoryName;
                    childrenReceiving.MaterialCategoryCode = shippingLock.MaterialCategoryCode;
                    childrenReceiving.MaterialGroupCode = shippingLock.MaterialGroupCode;
                    childrenReceiving.MaterialId = shippingLock.MaterialId;
                    childrenReceiving.Name = shippingLock.MaterialName;
                    childrenReceiving.Code = shippingLock.MaterialCode;
                    childrenReceiving.ModelSpec = shippingLock.ModelSpec;
                    childrenReceiving.QualityState = shippingLock.QualityState;
                    childrenReceiving.Price = shippingLock.Price;
                    childrenReceiving.ReceivePrice = shippingLock.Price;
                    childrenReceiving.UnitId = shippingLock.UnitId;
                    childrenReceiving.UnitName = shippingLock.UnitName;
                    childrenReceiving.ReceivedQty = shippingLock.OutQty;
                    childrenReceiving.Qty = shippingLock.OutQty;
                    childrenReceiving.TotalPrice = shippingLock.TotalPrice;
                    groupReceivingOrderDto.childrenReceivingOrders.Add(childrenReceiving);
                }

                return groupReceivingOrderDto;
            }
            else if(ordersn.Substring(0, 1).Contains("R"))
            {
                var receorder = Context.TReceivingOrderDetails.Where(x => x.OrderSn == ordersn);
                if (!receorder.Any())
                {
                    return null;
                }
                GroupReceivingOrderDto groupReceivingOrderDto = new GroupReceivingOrderDto();
                groupReceivingOrderDto.OrderSn = receorder.First().OrderSn;
                groupReceivingOrderDto.BillType = receorder.First().BillType;
                groupReceivingOrderDto.RelevanceOrderSn = receorder.First().RelevanceOrderSn;
                groupReceivingOrderDto.Agent = receorder.First().Agent;
                groupReceivingOrderDto.SupplierId = receorder.First().SupplierId;
                groupReceivingOrderDto.SupplierName = receorder.First().SupplierName;
                groupReceivingOrderDto.SupplierCode = receorder.First().SupplierCode;
                groupReceivingOrderDto.Contact = receorder.First().Contact;
                groupReceivingOrderDto.ContactMobile = receorder.First().ContactMobile;
                groupReceivingOrderDto.ProductDate = receorder.First().ProductDate;
                groupReceivingOrderDto.Remark = receorder.First().Remark;
                groupReceivingOrderDto.State = receorder.First().Status;
                groupReceivingOrderDto.ProductDate = receorder.First().ProductDate;

                var urlobj = Context.TReceivingOrderDetailFile.Where(x => x.ReceivingOrderSn == ordersn);
                List<FileClass> FileClasss = new List<FileClass>();
                foreach (var item in urlobj)
                {
                    FileClass file = new FileClass();
                    file.url = item != null ? item.FileUrl : "";
                    file.name = item.FileName;
                    //string url = item != null ? item.FileUrl : "";
                    FileClasss.Add(file);
                }
                groupReceivingOrderDto.File = FileClasss;

                foreach (var item in receorder)
                {
                    ChildrenReceivingOrder childrenReceiving = new ChildrenReceivingOrder();
                    childrenReceiving.Id = item.Id;
                    childrenReceiving.MakerialCategoryId = item.MaterialCategoryId;
                    childrenReceiving.MaterialCategoryName = item.MaterialCategoryName;
                    childrenReceiving.MaterialId = item.MaterialId;
                    childrenReceiving.Name = item.MaterialName;
                    childrenReceiving.Code = item.MaterialCode;
                    childrenReceiving.ModelSpec = item.ModelSpec;
                    childrenReceiving.QualityState = item.QualityState;
                    childrenReceiving.Price = item.Price;
                    childrenReceiving.ReceivedQty = item.ReceivedQty;
                    childrenReceiving.Qty = item.Qty;
                    childrenReceiving.TotalPrice = item.TotalPrice;
                    childrenReceiving.Remark = item.Remark;
                    childrenReceiving.UnitName = item.UnitName;
                    childrenReceiving.UnitId = item.UnitId;
                    childrenReceiving.MaterialGroupId = item.MaterialGroupId;
                    childrenReceiving.MaterialGroupCode = item.MaterialGroupId;
                    groupReceivingOrderDto.childrenReceivingOrders.Add(childrenReceiving);
                }
                return groupReceivingOrderDto;
            }
            else
            {
                return null;
            }
         
        }

        /// <summary>
        /// 修改入库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTReceivingOrderDetail(GroupReceivingOrderDto m, out string message)
        {
            message = "";
            //判断当前供应商是否存在
            var suppobj = Context.TSuppliers.AsNoTracking().FirstOrDefault(x => x.Code == m.SupplierCode);
            if (suppobj != null)
            {
                //m.SupplierId = suppobj.Id;
                //m.SupplierName = suppobj.Name;
                //修改已有的
                suppobj.Name = m.SupplierName;
                suppobj.Contact = m.Contact;
                suppobj.ContactMobile = m.ContactMobile;
                suppobj.ModifyDate = DateTime.Now;
                suppobj.ModifyUserId = m.NowUserId;
                suppobj.ModifyUserName = m.NowUserName;
                Context.TSuppliers.Update(suppobj);
            }
            else
            {
                TSupplier supplier = new TSupplier();
                //supplier.Code = m.SupplierCode;
                //supplier.Name = m.SupplierName;
                supplier.Contact = m.Contact;
                supplier.ContactMobile = m.ContactMobile;
                supplier.CreateDate = DateTime.Now;
                supplier.CreateUserId = m.NowUserId;
                supplier.CreateUserName = m.NowUserName;
                Context.TSuppliers.Add(supplier);
            }

            var receivingOrderDetailFileobj = Context.TReceivingOrderDetailFile.AsNoTracking().Where(x => x.ReceivingOrderSn == m.OrderSn);
            if (receivingOrderDetailFileobj.Any())
            {
                foreach (var item in receivingOrderDetailFileobj)
                {
                    var delList = Context.TReceivingOrderDetailFile.Remove(item);

                    //receivingOrderDetailFileobj.FileUrl = m.FileUrl;
                    //Context.TReceivingOrderDetailFile.Update(receivingOrderDetailFileobj);
                }
                foreach (var item in m.File)
                {
                    TReceivingOrderDetailFile receivingOrderDetailFile = new()
                    {
                        ReceivingOrderSn = m.OrderSn,
                        FileUrl = item.url,
                        FileName = item.name
                    };
                    Context.TReceivingOrderDetailFile.Add(receivingOrderDetailFile);
                }


            }
            else
            {
                //添加入库凭证
                foreach (var item in m.File)
                {
                    TReceivingOrderDetailFile receivingOrderDetailFile = new()
                    {
                        ReceivingOrderSn = m.OrderSn,
                        FileUrl = item.url,
                        FileName = item.name
                    };
                    Context.TReceivingOrderDetailFile.Add(receivingOrderDetailFile);
                }
            }
            var reorderlist = Context.TReceivingOrderDetails.AsNoTracking().Where(x => x.OrderSn == m.OrderSn);
            if (reorderlist != null)
                Context.TReceivingOrderDetails.RemoveRange(reorderlist);
            foreach (var item in m.childrenReceivingOrders)
            {
                TReceivingOrderDetail receivingOrderDetail = new TReceivingOrderDetail();
                receivingOrderDetail.OrderSn = m.OrderSn;
                receivingOrderDetail.BillType = m.BillType;
                receivingOrderDetail.RelevanceOrderSn = m.RelevanceOrderSn;
                receivingOrderDetail.Agent = m.Agent;
                receivingOrderDetail.SupplierId = m.SupplierId;
                receivingOrderDetail.SupplierCode = m.SupplierCode;
                receivingOrderDetail.SupplierName = m.SupplierName;
                receivingOrderDetail.Contact = m.Contact;
                receivingOrderDetail.ContactMobile = m.ContactMobile;
                receivingOrderDetail.ProductDate = m.ProductDate;
                receivingOrderDetail.CreateDate = DateTime.Now;
                receivingOrderDetail.MaterialCategoryId = item.MakerialCategoryId;
                receivingOrderDetail.UnitName = item.UnitName;
                if (item.UnitId != null && item.UnitId > 0)
                {
                    var unitobj = Context.TDictItems.Find(item.UnitId);
                    if (unitobj != null)
                    {
                        receivingOrderDetail.UnitId = unitobj.Id;
                        receivingOrderDetail.UnitName = unitobj.ItemName;
                    }
                }
                //装备名称
                receivingOrderDetail.MaterialCategoryName = item.MaterialCategoryName;
                receivingOrderDetail.MaterialId = item.MaterialId;
                receivingOrderDetail.MaterialName = item.Name;
                receivingOrderDetail.MaterialCode = item.Code;
                receivingOrderDetail.ModelSpec = item.ModelSpec;
                receivingOrderDetail.QualityState = item.QualityState;//质量等级
                receivingOrderDetail.ReceivedQty = item.ReceivedQty;
                receivingOrderDetail.Qty = item.ReceivedQty;
                receivingOrderDetail.TotalPrice = item.TotalPrice;
                receivingOrderDetail.Price = item.Price;
                receivingOrderDetail.Remark = m.Remark;

                //订单来源默认手动创建
                receivingOrderDetail.SourceType = 0;
                #region 审计字段
                receivingOrderDetail.ModifyUserId = m.NowUserId;
                receivingOrderDetail.ModifyUserName = m.NowUserName;
                receivingOrderDetail.ModifyDate = DateTime.Now;
                #endregion
                Context.TReceivingOrderDetails.Add(receivingOrderDetail);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 打印条码
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public List<TReceivingPrint> PrintReceiving(int OrderId)
        {
            var TReceivingOrderlist = Context.TReceivingOrderDetails.Where(x => x.Id == OrderId).ToList();
            List<TReceivingPrint> receivingPrintList = new List<TReceivingPrint>();

            foreach (var item in TReceivingOrderlist)
            {
                var list = Context.TReceivingGoodsDetails.Where(x => x.OrderDetailId == item.Id).ToList();

                var barcodeGroups = list.GroupBy(x => x.Barcode);

                foreach (var group in barcodeGroups)
                {
                    int totalQty = group.Count();

                    for (int i = 0; i < totalQty; i++)
                    {
                        TReceivingPrint receivingPrint = new TReceivingPrint();
                        receivingPrint.OrderSn = item.OrderSn;
                        receivingPrint.MaterialCategoryName = item.MaterialCategoryName;
                        receivingPrint.MaterialCategoryCode = item.MaterialCategoryCode;
                        receivingPrint.MaterialCode = group.Key;
                        receivingPrint.MaterialName = item.MaterialName;
                        receivingPrint.Qty = totalQty;

                        receivingPrintList.Add(receivingPrint);
                    }
                }
            }

            return receivingPrintList;
        }

        /// <summary>
        /// 判断库中是否存在此物料,没有则添加(物料表和库存表)
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <param name="mes"></param>
        /// <returns></returns>
        public bool DoesItExistMaterial(string OrderSn, string ReceivingPoint, string position, out string mes)
        {
            mes = "";
            List<TMaterial> materials = new List<TMaterial> { new TMaterial() };
            var list = Context.TReceivingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();
            foreach (var item in list)
            {
                var MaterialList = Context.TMaterial.Where(x => x.Code == item.MaterialCode).ToList();
                if (/*MaterialList != null &&*/ MaterialList.Count > 0)
                {
                    continue;
                }
                TMaterial material = new TMaterial();
                
                material.Code = item.MaterialCode;
                material.Name = item.MaterialName;
                material.ModelSpec = item.ModelSpec;
                material.UnitId = item.UnitId;
                material.UnitName = item.UnitName;
                material.CreateDate = DateTime.Now;
                material.QualityState = item.QualityState;
                material.MaterialCategoryId = item.MaterialCategoryId;
                material.ModelSpec = item.ModelSpec;
                material.UnitId = item.UnitId;
                material.UnitName = item.UnitName;
                material.CreateDate = DateTime.Now;
                material.QualityState = item.QualityState;
                material.MaterialCategoryCode = Context.TMaterialCategories.Where(x => x.Name == item.MaterialCategoryName).First().Code;
                material.MaterialCategoryName = item.MaterialCategoryName;
                //material.MaterialGroupCode = item.MaterialGroupId;
                //material.MaterialGroupId = Context.TMaterialGroups.First(x => x.Code == item.MaterialGroupId).Id;
                material.ReceivePrice = item.Price;
                material.ReceivedQty = (int?)item.ReceivedQty;
                material.InventoriesTypeStatus = 1;
                materials.Add(material);
                Context.TMaterials.Add(material);
                if (Context.SaveChanges() <= 0)
                {
                    mes = "添加物料表失败";
                    return false;
                }
            }

            //List<TInventory> inventories = new List<TInventory>();
            //foreach (var item in list)
            //{
            //    var InventoryList = Context.TInventory.Where(x => x.MaterialCode == item.MaterialCode).ToList();
            //    if ( /*InventoryList != null*/ InventoryList.Count > 0)
            //    {
            //        continue;
            //    }
            //    TInventory inventory = new TInventory();
            //    //inventory.LocationName = item.CellName;
            //    //inventory.LocationId = Context.TCells.Where(x => x.Name == item.CellName).First().Id;
            //    //inventory.LocationCode = Context.TCells.Where(x => x.Name == item.CellName).First().Code;
            //    inventory.CreateDate = DateTime.Now;
            //    inventory.MaterialId = item.MaterialId;
            //    inventory.MaterialName = item.MaterialName;
            //    inventory.MaterialCode = item.MaterialCode;
            //    //inventory.AvailableQty = item.ReceivedQty;
            //    inventory.UnitId = item.UnitId;
            //    inventory.UnitName = item.UnitName;
            //    inventory.QualityState = item.QualityState;
            //    inventory.ModelSpec = item.ModelSpec;
            //    inventory.LocationCode = ReceivingPoint;
            //    //缺仓位
            //    inventory.LocationCode = position;
            //    inventory.MaterialCategoryId = item.MaterialCategoryId;
            //    inventory.MaterialCategoryName = item.MaterialCategoryName;
            //    inventory.MaterialCategoryCode = item.MaterialCategoryCode;
            //    inventory.MaterialGroupId = item.MaterialGroupId;
            //    inventory.InventoriesTypeStatus = 1;
            //    inventory.Price = item.Price;
            //    inventory.MaterialId = Context.TMaterial.First(x => x.Code == item.MaterialCode).Id;
            //    inventories.Add(inventory);
            //    Context.TInventory.Add(inventory);

            //    TInventoryLog tlog = new TInventoryLog();


            //}
            //if (Context.SaveChanges() > 0)
            //{
            //    mes = "添加物料成功";
            //    return true;
            //}
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="UnitId"></param>
        /// <returns></returns>
        public UnitOfMeasurementRules GetUnitRulesList(int? UnitId)
        {
            var list = Context.UnitOfMeasurementRules.Where(x => x.frontUnitId == UnitId);
            if (list.Count() <= 0)
            {
                return null;
            }
            return list.First();
        }

        public TMateialCategoryAddNumber GetCategoryNumByCode(int categoryId, out string message)
        {
            message = "";
            var categoryList = Context.TMaterialCategories.Find(categoryId);
            if (categoryList == null)
            {
                message = "未查询到此装备名称";
                return null;
            }
            var numList = Context.TMateialCategoryAddNumber.Where(x => x.CategoryCode == categoryList.Code).ToList();
            if (numList.Count <= 0)
            {
                TMateialCategoryAddNumber num = new TMateialCategoryAddNumber();
                num.CategoryCode = categoryList.Code;
                num.CategoryName = categoryList.Name;
                num.CategoryId = categoryList.Id;
                num.Number = "001";
                Context.TMateialCategoryAddNumber.Add(num);
                if (Context.SaveChanges() >= 0)
                {
                    return num;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                int intValue = int.Parse(numList.FirstOrDefault().Number) + 1;
                string newValue = intValue.ToString("000");
                numList.FirstOrDefault().Number = newValue;
                Context.TMateialCategoryAddNumber.Update(numList.FirstOrDefault());
                if (Context.SaveChanges() >= 0)
                {
                    return Context.TMateialCategoryAddNumber.FirstOrDefault(x => x.CategoryCode == numList.FirstOrDefault().CategoryCode);
                }
                return null;
            }
        }


        public decimal? GetMsgByCellAndCode(string cellCode, string materialCode)
        {
            var inventoryList = Context.TInventories.Where(x => x.LocationCode == cellCode && x.MaterialCode == materialCode).ToList();
            if(inventoryList.Count == 0)
            {
                return 0;
            }
            return inventoryList.FirstOrDefault().AvailableQty;
        }
    }
}
